/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javabeans.JBCliente;
import javabeans.JBUsuario;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import persistencia.ISistema;

/**
 *
 * @author bruno
 */
public class registroClienteServlet extends HttpServlet {

    ISistema i;
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws Servle        tException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    @Override
    public void init() throws ServletException {
        super.init();
        /*Se adquieren los parametros configurados en el deployment describer a 
         * nivel del contexto*/
        try {
            ServletContext context = this.getServletContext();
            i = persistencia.Fabrica.getPersistenciaSistema(context);

        } catch (Exception exc) {
            throw new UnavailableException("No se puedo instanciar el servlet" + exc.toString());
        }
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                                            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        
        try {            
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            
            int ci = Integer.parseInt(request.getParameter("ci"));
            String user = request.getParameter("usuario");
            String password = request.getParameter("password");
            String nombre = request.getParameter("nombre");
            String email = request.getParameter("email");
            Date fechaNacimiento = df.parse(request.getParameter("fechaNac"));
            
            JBUsuario usuario = new JBUsuario();
            JBCliente cliente = new JBCliente();
            
            usuario.setCi(ci);
            usuario.setUsuario(user);
            usuario.setPassword(password);
            usuario.setTipoUsuario("cliente");
            
            cliente.setCi(ci);
            cliente.setNombre(nombre);
            cliente.setFechaNacimiento(fechaNacimiento);
            cliente.setEmail(email);
            cliente.setUsuario(usuario);
            
            JBCliente clienteAgregado = i.crearCliente(cliente);
            
            if(clienteAgregado != null){
                session.setAttribute("login", clienteAgregado);
                response.sendRedirect("registroCompleto.jsp");
            }else{
                session.setAttribute("error", "Error al agregar el cliente");
                request.getRequestDispatcher("registroCliente.jsp").forward(request, response);
            }
            
            
        } catch (SQLException ex) {
            session.setAttribute("error", "Error al registrarse");
                    
        } catch (ParseException ex) {
            session.setAttribute("error", "Error al enviar los datos");
        } finally {            
            request.removeAttribute("ci");
            request.removeAttribute("usuario");
            request.removeAttribute("password");
            request.removeAttribute("nombre");
            request.removeAttribute("email");
            request.removeAttribute("fechaNac");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
